package com.example.notering;

import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.dao.Diary;
import com.example.data.CacheDiary;

public class AddDiaryActivity extends Activity {

	private EditText editDiarytitle;
	private EditText editDiarycontent;
	private Button buttonDiaryclear;
	private Button buttonDiarysave;
	private Button buttonDiaryimage;
	private TextView editDiarytime;
	private Diary diary;
	private Uri originalUri;
	private Bitmap bitmap;
	private ContentResolver resolver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_diary);
		
		init();
		setListener();
	}

	private void setListener() {
		//清空输入框
		buttonDiaryclear.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				editDiarytitle.setText("");
				editDiarycontent.setText("");
			}});
		//保存
		buttonDiarysave.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				diary.setTitle(editDiarytitle.getText().toString());
				diary.setContent(editDiarycontent.getText().toString());
				
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				try {
					Date date = sdf.parse(editDiarytime.getText().toString());
					diary.setDate(date);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				
				CacheDiary.getInstance(AddDiaryActivity.this).saveDiary(diary);
				finish();
			}});
		//插入图片
		buttonDiaryimage.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
                getImage.addCategory(Intent.CATEGORY_OPENABLE);
                getImage.setType("image/*");
                startActivityForResult(getImage, 1);
			}});
	}

	private void init() {
		diary = new Diary();
		editDiarytime = (TextView)findViewById(R.id.diary_time);
		editDiarytitle = (EditText)findViewById(R.id.diary_title);
		editDiarycontent = (EditText)findViewById(R.id.diary_content);
		buttonDiaryclear = (Button)findViewById(R.id.diary_clear);
		buttonDiarysave = (Button)findViewById(R.id.diary_save);
		buttonDiaryimage = (Button)findViewById(R.id.diary_image);
		// 系统时间
		String time = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis());
		editDiarytime.setText(time);
		
		//多行编辑
		editDiarycontent.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
		editDiarycontent.setText("数据测试数据测试数据测试数据测试数据测试数据ddsaadsasasddsasadsSD卡哦多尅祭扫ID竞赛噢见到is测试");  
		editDiarycontent.setSingleLine(false);  
		editDiarycontent.setHorizontallyScrolling(false);  
		
	}
	
	private SpannableString getBitmap(Bitmap pic, Uri uri) {
        String path = uri.getPath();
        SpannableString s = new SpannableString(path);
        ImageSpan span = new ImageSpan(this, pic);
        s.setSpan(span, 0, path.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return s;
    }
	
	private void insertIntoEditText(SpannableString s) {
		Editable et = editDiarycontent.getText();// 先获取Edittext中的内容
		int start = editDiarycontent.getSelectionStart();
		et.insert(start, s);// 设置s要添加的位置
		editDiarycontent.setText(et);// 把et添加到Edittext中
		editDiarycontent.setSelection(start + s.length());// 设置Edittext中光标在最后面显示
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        resolver = getContentResolver();
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                originalUri = intent.getData();
                try {
                    Bitmap originalBitmap = BitmapFactory.decodeStream(resolver
                            .openInputStream(originalUri));
                    bitmap = resizeImage(originalBitmap, 300, 300);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                if (bitmap != null) {
                    insertIntoEditText(getBitmap(bitmap, originalUri));
                } else {
                    Toast.makeText(AddDiaryActivity.this, "获取图片失败",
                            Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (bitmap != null) {
        }
    }

	private Bitmap resizeImage(Bitmap originalBitmap, int i, int j) {
		Bitmap bitMapImage = null;
        Options options = new Options();
        options.inJustDecodeBounds = true;
		try {
			BitmapFactory.decodeStream(resolver.openInputStream(originalUri), null, options);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}  
        double sampleSize = 0;
        Boolean scaleByHeight = Math.abs(options.outHeight - i) >= Math
                .abs(options.outWidth - j);
            if (options.outHeight * options.outWidth * 2 >= 1638) {
            sampleSize = scaleByHeight ? options.outHeight / i
                    : options.outWidth / j;
            sampleSize = (int) Math.pow(2d,
                    Math.floor(Math.log(sampleSize) / Math.log(2d)));
        }
        options.inJustDecodeBounds = false;
        options.inTempStorage = new byte[128];
        while (true) {
            try {
                options.inSampleSize = (int) sampleSize;
                bitMapImage = BitmapFactory.decodeStream(resolver.openInputStream(originalUri), null, options);  
                  break;
            } catch (Exception ex) {
                try {
                    sampleSize = sampleSize * 2;
                } catch (Exception ex1) {
                  }
            }
        }
        return bitMapImage;
	}
}
